package com.example.health_life.service;

import com.example.health_life.dao.MyCourse;
import com.example.health_life.dao.MyCourseRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class MyCourseServiceImpl implements  MyCourseService{

    @Autowired
    private MyCourseRepository myCourseRepository;

    @Override
    public List<MyCourse> getMyCourseList(Integer status) {
        if(status == 0){
            return myCourseRepository.findAll();
        }
        List<MyCourse> myCourses = null;
        if(status == 1){
            myCourses = myCourseRepository.findByStatus((byte)(1));
        }
        if(status == -1){
            myCourses = myCourseRepository.findByStatus((byte)(-1));
        }
        return myCourses;
    }

    @Override
    public MyCourse getMyCourseById(Integer id) {
        return myCourseRepository.findById(id).get();
    }

    @Override
    public List<MyCourse> getMyCourseByUserId(Integer userId, Integer status) {
        if(status == 0){
            return myCourseRepository.findByUserId(userId);
        }
        List<MyCourse> myCourses = null;
        if(status == 1){
            myCourses = myCourseRepository.findByUserIdAndStatus(userId, (byte)(1));
        }
        if(status == -1){
            myCourses = myCourseRepository.findByUserIdAndStatus(userId, (byte)(-1));
        }
        return myCourses;
    }

    @Override
    public Integer addMyCourse(MyCourse myCourse) {
        //          默认status为1
        myCourse.setStatus((byte)1);
        //        默认添加时间为当前时间
        myCourse.setAddTime(java.time.Instant.now());
        return myCourseRepository.save(myCourse).getId();
    }

    @Override
    public Integer deleteMyCourse(Integer id) {
        //查找记录是否存在
        MyCourse myCourse = myCourseRepository.findById(id).orElseThrow(()->new IllegalStateException("记录不存在"));
        
        // 检查是否存在冲突记录
        byte newStatus = (byte)(-1 * myCourse.getStatus());
        List<MyCourse> existingCourses = myCourseRepository.findByUserIdAndStatus(myCourse.getUserId(), newStatus);
        for (MyCourse existing : existingCourses) {
            if (existing.getCourseId().equals(myCourse.getCourseId())) {
                // 如果存在冲突记录，先删除冲突记录
                myCourseRepository.delete(existing);
            }
        }
        
        //将状态改为相反数
        myCourse.setStatus(newStatus);
        myCourseRepository.save(myCourse);
        return id;
    }

    @Override
    public Integer getMyCourseStatusByUserIdAndCourseId(Integer userId, Integer courseId) {
        List<MyCourse> myCourses = myCourseRepository.findByUserId(userId);
        for (MyCourse course : myCourses) {
            if (course.getCourseId().equals(courseId)) {
                return course.getId();
            }
        }
        return 0;  // 如果不存在记录，返回0
    }
}
